package com.mioto.ld.communication.mqtt;

import com.mioto.ld.module.network.model.Network;
import com.mioto.ld.module.network.service.INetworkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author mioto-qinxj
 * @date 2024/5/6
 * @desc 项目启动 订阅主题
 */
@Slf4j
@Component
public class MqttClientListener implements ApplicationListener<ContextRefreshedEvent> {
    @Resource
    private INetworkService networkService;
    private final AtomicBoolean isInit = new AtomicBoolean(false);
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //防止重复触发
        if (!isInit.compareAndSet(false, true)) {
            return;
        }
        log.info("系统启动,查询数据库网络组件,准备开启mqtt连接...");
        List<Network> networkList = networkService.findList(new Network());
        if (!CollectionUtils.isEmpty(networkList)) {
            for (Network network : networkList) {
                MqttHelper.start(network);
            }
        }
    }
}
